package com.tianheng.wanzhou.datacollecting.netty.lengganji;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.Cushaji;
import com.tianheng.wanzhou.datacollecting.db.entity.FreezingDryer10000005;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.ICushajiService;
import com.tianheng.wanzhou.datacollecting.db.service.IFreezingDryer10000005Service;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.FloatOperate;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import com.tianheng.wanzhou.datacollecting.util.TqlHexchange;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ql
 * @Date: 2020/5/12 14:26
 * @Version 1.0
 */
@Slf4j
@Component(value = "lengganjiHandler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IFreezingDryer10000005Service freezingDryer10000005Service;
    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        freezingDryer10000005Service = this.freezingDryer10000005Service;
//        jedis = this.jedis;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 3).eq("status", 1);
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            FreezingDryer10000005 lengganji = new FreezingDryer10000005();
            lengganji.setMachineIp(machine.getMacIp());
            lengganji.setMachineId(machine.getMacId());
            lengganji.setCompany(machine.getCompany());
            lengganji.setWorkshop(machine.getWorkshop());

            String length = str.substring(4, 6).toLowerCase();
            String data = str.substring(6, str.length() - 4);
            char[] binaries = TqlHexchange.hexString2binaryString(data.substring(0,4)).toCharArray();
            lengganji.setCoolantHVAbnormal(Character.digit(binaries[15], 2));
            lengganji.setCoolantLVAbnormal(Character.digit(binaries[14], 2));
            lengganji.setOilPressureDAbnormal(Character.digit(binaries[13], 2));
            lengganji.setShortfallInOilAbnormal(Character.digit(binaries[12], 2));
            lengganji.setOweTheReverseAbnormal(Character.digit(binaries[11], 2));
            lengganji.setOverheatAbnormal(Character.digit(binaries[10], 2));
            lengganji.setOverloadAbnormal(Character.digit(binaries[9], 2));
            lengganji.setDischargeTemperature(String.valueOf(binaries[8]));
            lengganji.setRemoteStartSignal(Character.digit(binaries[7], 2));
            char[] binaries1 = TqlHexchange.hexString2binaryString(data.substring(4,8)).toCharArray();
            lengganji.setMasterContactor(Character.digit(binaries1[15], 2));
            lengganji.setTrigonContactor(Character.digit(binaries1[14], 2));
            lengganji.setYContactor(Character.digit(binaries1[13], 2));
            lengganji.setAbnormalSignalOutput(Character.digit(binaries1[12], 2));
            lengganji.setDeliveryValveStart(Character.digit(binaries1[10], 2));
            lengganji.setQuarterValveStart(Character.digit(binaries1[9], 2));
            lengganji.setHalfValveStart(Character.digit(binaries1[8], 2));
            lengganji.setDewPointTemperature(TqlHexchange.zcString(data.substring(8,12)));


            freezingDryer10000005Service.saveOrUpdate(lengganji);

        }finally {
            ReferenceCountUtil.release(msg);
        }
        ctx.channel().close();
        ctx.close();

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
